package com.nommon.menu;

import android.graphics.Canvas;

public class UpdateNDrawThread extends Thread {
	static final int FPS = 25;
	private GameView view;
	private boolean running = false;

	public UpdateNDrawThread(GameView view) {
		this.view = view;
	}

	public void setRunning(boolean run) {
		running = run;
	}

	@Override
	public void run() {
		int msPerFrame = 1000 / FPS;
		long previousStartTime = System.currentTimeMillis();
		while (running) {
			Canvas c = null;
			long startTime = System.currentTimeMillis();
			try {
				c = view.getHolder().lockCanvas();
				synchronized (view.getHolder()) {
					view.onUpdate((startTime - previousStartTime)/1000f);
					view.onDraw(c);
				}
			} finally {
				if (c != null) {
					view.getHolder().unlockCanvasAndPost(c);
				}
			}
			previousStartTime = startTime;
			long endTime = System.currentTimeMillis();
			long sleepTime = msPerFrame - (endTime - startTime);
			if (sleepTime < 0){
				sleepTime = 10;
			}
			try {
				sleep(sleepTime);
			} catch (Exception e) {}

		}

	}

}
